package models

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"github.com/astaxie/beego/orm"
	"object/go_cms/valid"
	"strconv"
)

type AdminModels struct {
	agm AdminGroupModels
}

type Admin struct {
	Id        int64        `orm:"pk;auto"`
	User_name string       `orm:"size(30);default:('')"`
	Password  string       `orm:"size(128);default:('')"`
	Head      string       `orm:"size(255);default('')"`
	Status    int          `orm:"size(2);default:(1)"`
	Group     []AdminGroup `orm:"-"`
}

func init() {
	orm.RegisterModel(new(Admin))
}

//登录
func (mod *AdminModels) LoginAdmin(user string, pwd string) (Admin, error) {
	m := md5.New()
	m.Write([]byte(pwd))
	pwdstr := hex.EncodeToString(m.Sum(nil))

	ps := getQueryTable("admin")
	ps = ps.Filter("password", pwdstr)
	ps = ps.Filter("user_name", user)

	admin := Admin{}
	//其他状态
	err := ps.One(&admin)
	return admin, err
}

//获取指定信息
func (mod *AdminModels) GetAdmin(id int64) (Admin, error) {
	ps := getQueryTable("admin")
	admin := Admin{Id: id}
	err := ps.Filter("id", id).One(&admin)
	ag := AdminGroupModels{}
	admin.Group, _ = ag.Query(id)
	return admin, err
}

//获取列表,[],int
func (mod *AdminModels) QueryByPageAdmin(param map[string]interface{}) ([]Admin, int64) {
	var list []Admin
	ps := getQueryTable("admin")

	if param["limit"] == nil {
		param["limit"] = 10
	}
	if param["page"] == nil {
		param["page"] = 1
	}
	if param["user_name"] != nil {
		ps = ps.Filter("user_name", param["user_name"])
	}
	if param["status"] != nil {
		ps = ps.Filter("status", param["status"])
	}
	page, _ := param["page"].(int)
	limit, _ := param["limit"].(int)
	off := (page - 1) * limit

	ps.Limit(limit, off).All(&list)
	count, _ := ps.Count()
	return list, count
}

//插入
func (mod *AdminModels) InsertAdmin(param map[string]interface{}) (int64, error) {
	admin := Admin{}
	//验证
	bo, str := valid.ValidAddAdmin(param)
	if !bo {
		return 0, errors.New(str)
	}

	admin.User_name = param["user_name"].(string)
	if param["status"] != nil {
		admin.Status, _ = strconv.Atoi(param["status"].(string))
	}
	if param["head"] != nil {
		admin.Head = param["head"].(string)
	}
	m := md5.New()
	m.Write([]byte(param["password"].(string)))
	admin.Password = hex.EncodeToString(m.Sum(nil))
	o := orm.NewOrm()
	err := o.Begin()
	row, err := o.Insert(&admin)
	if err != nil {
		_ = o.Rollback()
		return 0, err
	}
	if param["group_id"] != nil {
		var ag = make(map[string]interface{})
		ag["admin_id"] = row
		ag["group_id"] = param["group_id"]

		_, err = mod.agm.Update(ag)
		if err != nil {
			_ = o.Rollback()
			return 0, err
		}
	}
	_ = o.Commit()
	return row, err
}

//编辑
func (mod *AdminModels) UpdateAdmin(param map[string]interface{}) (int64, error) {
	admin := Admin{}
	admin.Id, _ = strconv.ParseInt(param["id"].(string), 10, 64)

	//验证
	bo, str := valid.ValidEditAdmin(param)
	if !bo {
		return 0, errors.New(str)
	}
	o := orm.NewOrm()
	err := o.Begin()
	_ = o.Read(&admin)
	if param["password"] != nil {
		m := md5.New()
		m.Write([]byte(param["password"].(string)))
		admin.Password = hex.EncodeToString(m.Sum(nil))
	}
	if param["user_name"] != nil {
		admin.User_name = param["user_name"].(string)
	}
	if param["status"] != nil {
		admin.Status = param["status"].(int)
	}
	if param["head"] != nil {
		admin.Head = param["head"].(string)
	}

	row, err := o.Update(&admin)
	if err != nil {
		_ = o.Rollback()
		return 0, err
	}
	if param["group_id"] != nil {
		var ag = make(map[string]interface{})
		ag["admin_id"] = admin.Id
		ag["group_id"] = param["group_id"]
		_, err = mod.agm.Update(ag)
		if err != nil {
			_ = o.Rollback()
			return 0, err
		}
	}
	_ = o.Commit()
	return row, err
}

//删除
func (mod *AdminModels) DeleteAdmin(id int64) (int64, error) {
	o := orm.NewOrm()
	row, err := o.Delete(&Admin{Id: id}, "Id")
	if err == nil {
		ag := AdminGroupModels{}
		_, _ = ag.Delete(id)
	}
	return row, err
}
